<template>
    <Dialog
      :show="dialogConfig.show"
      :title="dialogConfig.title"
      :buttons="dialogConfig.buttons"
      :showCancel="true"
      @close="dialogConfig.show = false"
        :width="600+'px'"
    >
     <div >
        <el-form
        :model="formData"
        :rules="rules"
        ref="formDataRef"
        label-width="120px"
        @submit.prevent
      >

        <!-- 新增用户搜索 -->
        <el-form-item label="选择用户" prop="userId">
          <el-autocomplete
            v-model="searchKey"
            :fetch-suggestions="searchUser"
            placeholder="输入用户名搜索"
            @select="handleUserSelect"
            clearable
            :loading="loading"
>
            <template #default="{ item }">
              <span>{{ item.userName }}</span>
              <span style="margin-left:15px;color:#909399">{{ item.phone }}</span>
            </template>
          </el-autocomplete>
        </el-form-item>

        <el-form-item label="用户名" prop="userName">
          <el-input
            v-model="formData.userName"
            disabled
            placeholder="选择用户后自动填充"
          />
        </el-form-item>

        <el-form-item label="电话" prop="contact">
          <el-input
            v-model="formData.contact"
            disabled
            placeholder="选择用户后自动填充"
          />
        </el-form-item>

        <el-form-item label="实验室名称" prop="name" label-width="120px">
          <el-input placeholder="请输入实验室名称不超过400字符" :maxLength="400" v-model="formData.name" />
        </el-form-item>

        <el-form-item label="地址" prop="location"  label-width="120px">
          <el-input  type="textarea"
          :maxlength="400"
          show-word-limit
          placeholder="请输入实验室地址"
          v-model="formData.location" />
        </el-form-item>

      </el-form>
     </div>
    </Dialog>
  </template>

  <script setup>
  import { debounce } from "lodash-es";
  import { ref, reactive, getCurrentInstance, nextTick } from "vue";
  const { proxy } = getCurrentInstance();

  const dialogConfig = ref({
    show: false,
    title: "新增图书",
    buttons: [
      {
        type: "primary",
        text: "确定",
        click: (e) => {
          submitForm();
        },
      },
    ],
  });

  const formData = ref({});
  const formDataRef = ref();

  const searchKey = ref("")
  // 新增方法 - 用户搜索
  const searchUser = debounce(async (query, cb) => {
  if (!query) return cb([]);
  const result = await proxy.Request({
    url: "/settings/loadAccountList",
    params: { userNameFuzzy: query },
  });
  cb(result.data.list || []);
}, 500); // 300ms 防抖


// 新增方法 - 用户选择
 const handleUserSelect = (user) => {
  searchKey.value = user.userName;
  formData.value = {
    userId: user.userId,
    userName: user.userName,
    contact: user.phone,
    email: user.email
  }
 }

 const loadUserInfo = async (userId) => {
    const result = await proxy.Request({
      url: "/settings/getAccountByUserId",
      params: {
         userId: userId,
      }
    }
  )
  if(!result){
    return;
  }
  formData.value.userId =result.data.userId;
  formData.value.userName =result.data.userName;
  formData.value.phone =result.data.phone;
}


  const rules = {
    userName: [{ required: true, message: "请先选择实验室管理员" }],
    name: [{ required: true, message: "请输入实验室名称" }],
    location: [{ required: true, message: "请输入实验室地址" }],

  };

  const showEdit = (data) => {
    dialogConfig.value.show = true;
    nextTick(() => {
      formDataRef.value.resetFields();
      if (data.laboratoryId == null) {
        dialogConfig.value.title = "新增实验室信息";
      } else {
        dialogConfig.value.title = "修改实验室信息";
        loadUserInfo(data.userId);
        formData.value = data;
      }
    });
  };

  defineExpose({
    showEdit,
  });

  const emit = defineEmits(["reload"]);
  const submitForm = async () => {
    formDataRef.value.validate(async (valid) => {
      if (!valid) {
        return;
      }
      let params = {};
      Object.assign(params, formData.value);

      let result = await proxy.Request({
        url: "/laboratory/saveLaboratory",
        params,
      });
      if (!result) {
        return;
      }
      dialogConfig.value.show = false;
      proxy.Message.success("保存成功");
      emit("reload");
    });
  };
  </script>

  <style lang="scss" scoped>
  .check-span-item {
    float: left;
    margin-right: 10px;
    line-height: 20px;
  }
  </style>
